from flask import abort
from flask import current_app
from flask import render_template, jsonify
from flask import request

from info.models import News
from info.tools.response_code import RET
from . import news_blu


@news_blu.route("")
def news_show():
    try:
        news = News.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    if not news:
        abort(404)

    new_list = []
    for new in news:
        new_list.append(new.to_dict())

    return render_template("news.html", data=new_list)


@news_blu.route("/index")
def news_content():
    id = request.args.get("newsid")
    print(id)
    if not id:
        return jsonify(errno=RET.NODATA, errmsg='缺少参数')

    try:
        id = int(id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="参数错误")

    try:
        news = News.query.get(id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    if not news:
        abort(403)

    new_list = []
    new_list.append(news.to_dict())

    return render_template("newsshow.html", data=new_list)

